import {useState,useEffect} from 'react'
import useStorage from '../useStorage'
import lodash from 'lodash'
import {useLayout} from '@/layout/LayoutProvider'
export const useMenus = (filter=true)=>{
    const {state} = useLayout()
    const {menus:routerMenus} = state
    const [permissions,] = useStorage('permissions')
    const [menus,setMenus] = useState([])
    const filterMenus = () => {
        const filter = (list) => {
            return list.filter((item) => {
                if (item.children && item.children.length > 0) {
                    item.children = filter(item.children)
                }
                if(!item.access){
                    return true
                }
                return permissions && permissions.some((permission) => {
                    return permission === '*' || permission.startsWith(item.access)
                })
            })
        }
        return filter(lodash.cloneDeep(routerMenus))
    }
    useEffect(()=>{
        if(permissions && permissions.length>0){
            setMenus(filter ? filterMenus() : routerMenus)
        }else{
            setMenus(routerMenus)
        }
    },[permissions,routerMenus])
    return menus
}